import React, {Component,}from 'react'
import {connect,} from 'react-redux'
import {withRouter,} from 'react-router-dom'

// components
import ConsumePopup from "./ConsumePopup/ConsumePopup"
import GiftPopup from "./GiftPopup/GiftPopup"
import ChatRoomFooter from "./ChatRoomFooter/ChatRoomFooter"
import GiftNotice from "./GiftNotice/GiftNotice"
import DialogueContainer from "./Dialogue/Dialogue"

// constants
import constants from "../../../../../utils/constants"
import {log,} from "../../../../../utils/commonfunc"
import {Toast} from "antd-mobile";
import LocalStorageService from "../../../../../utils/LocalStorageService";
import {getChatTokenReq, getVisitorChatTokenReq, sendChatMsgReq} from "../../../../../apis/goApis";


class ChatRoom extends Component {

    constructor(props) {
        super(props)
        this.uid = localStorage.getItem('userid')
        this.login = LocalStorageService.get('isLogin')
        this.matchId = this.props.match.params.gameId
        this.state = {
            msg: '',
            inputTouched: false,
            popUp: {
                consume: false,
                gift: false,
            },
        }
    }

    componentDidMount() {

        if (this.props.holdon) {
            return
        } else {
            this.connect()
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (prevProps.holdon === true && prevProps.connectWsOk === false && this.props.connectWsOk === true) {
            console.log('connectOk')
            this.connect()
        }
    }

    connect() {
        this.getToken()
            .then((res) => {
                const ws = new WebSocket(constants.wsUrl2)
                const hid = 'login'
                // const quns = [matchId]
                const quns = []
                const frds = []
                let act, token
                if (this.uid) {
                    const t = res?.data?.ok
                    if (t) {
                        token = t
                        act = this.uid
                    }
                } else {
                    token = res?.data?.ok?.tk
                    act = res?.data?.ok?.act
                }
                const data = {
                    token,
                    act,
                    quns,
                    frds,
                    hid,
                }
                this.props.onConnectWs({ws, msg: data,})
            })
    }

    // 挂载组件的时候清除 ws 实例
    componentWillUnmount() {
        this.props.onChatWsClose()
    }

    getToken = async () => {
        const uid = this.uid
        const login = this.login
        if (login) {
            return await getChatTokenReq({uid,})
        } else {
            return await getVisitorChatTokenReq()
        }
    }

    onInputFocus = () => {
        this.setState({
            inputTouched: true,
        })
    }

    onInputBlur = () => {
        this.setState({
            inputTouched: false,
        })
    }
    

    connectWs = (token, type) => {

        const o = {
            live: `${constants.wsUrl}/ww`,
            game: `${constants.wsGameUrl}/ww`
        }
        const wsUrl = o[type]
        const ws = new WebSocket(wsUrl)

        const uid = localStorage.getItem('userid')
        // const anchorName = '平台'

        // Id(pin):"ded65287-b39b-4f04-977c-7caf75e7478d"
        // Username(pin):"18859900505"
        // Pwd(pin):""
        // Viplevel(pin):14
        // Gold(pin):9238
        // Gender(pin):0
        // Iconurl(pin):"http://123.207.85.242/try/go/avatar/ded65287-b39b-4f04-977c-7caf75e7478d.jpg#0.7938720239309662"
        // Nickname(pin):"59900505"
        // Mobile(pin):"18859900505"
        // Wxid(pin):""
        // Tokenuuid(pin):"GiQy54RcLSiuL9CHUlIuQNS8VCNLhOdY"
        // Realname(pin):""
        // Idnumber(pin):""
        // Email(pin):""
        // Exp(pin):10403
        // Packet(pin):"[[2,100],[3,10],[6,105],[10001,3],[20001,1],[8,160],[7,100],[5,4],[4,4]]"
        // Vip(pin):2
        // Vipst(pin):1584500547
        // IsStar(pin):false
        // IsShowing(pin):false
        // initFlag(pin):1
        const msg = {
            c: 3,
            token,
            // game,
            // viplevel,
            // nickname,
            uid,
            // anchorName,
            // vip,
        }
        this.props.onConnectWs({ws, msg,})
    }
    // events
    // 礼物 充值 弹窗
    onPopUp = (key) => {
        // const uid = localStorage.getItem('userid')
        // const err = this.props.chat.err
        this.setState({
            popUp: {
                [key]: true,
            },
        })

        // this.props.fetchUserDetail({uid,})
        //     .then(() => {
        //
        // })

    }

    onClose = key => {
        // const err = this.props.chat.err
        this.setState({
            popUp: {
                [key]: false,
            },
        })
        // const uid = localStorage.getItem('userid')
        // this.props.fetchUserDetail({uid,})
    }

    // 聊天输入条
    onChatInputChange = e => {
        const v = e.target.value
        this.setState({msg: v,})
    }

    // 发送聊天内容
    onChatInputSubmit = e => {
        // const w = e.which
        // if (w === 13) {
        //     e.preventDefault()
        //     this.sendMsg(this.state.msg)
        //     this.setState({msg: '',})
        //     e.target.blur()
        // }
        e.preventDefault()
        if (this.state.msg.length === 0) {
            return
        }
        this.sendMsg(this.state.msg)
        this.setState({msg: '',})
        e.target.blur()
    }

    // 打赏动画监听
    onAnimationEnd = (index, e) => {

        let arr = this.props.gifts
        arr[index].showed = true
        this.setState({
            gifts: arr,
        })

    }

    // actions
    // 接受 WebSocket 消息
    alertWsErr = msg => {
        log(msg)
    }

    addWsMsg = msg => {
        const {c,} = msg
        const cToAction = {
            1: this.addDialogue,
            2: this.addGift,
            3: this.addWelcome,
            4: this.addLeave,
        }
        cToAction[c](msg)
    }

    addDialogue = msg => {
        this.setState({dialogues: [...this.state.dialogues, msg],})
    }

    addGift = msg => {
        const gift = msg
        gift.showed = false
        const gs = this.state.gifts
        gs.push(gift)
        this.setState({gifts: gs,})
    }

    addWelcome = msg => {
        this.setState({dialogues: [...this.state.dialogues, msg,],})
        this.setState({users: [...this.state.users, msg,]})
    }

    addLeave = msg => {
        const users = this.state.users
        const i = users.findIndex(user => user.id === msg.id)
        users.splice(i, 1)
        this.setState({users: users,})
    }

    checkFirstMsg = () => {
        const storage = LocalStorageService
        const key = 'first-chat'
        const first = storage.get(key)
        const now = new Date()
        if (first === null) {
            storage.save(key, now)
            this.props.doGetChatExp()
        } else {
            const parsed = Date.parse(first)
            const diff = now - parsed
            const day = 86400000
            if (diff > day) {
                storage.save(key, now)
                this.props.doGetChatExp()
            }
        }
    }

    // 客户端发送消息
    // 发送聊天消息
    sendMsg = msg => {
        const m = {
            c: 1,
            msg,
            viplevel: this.props.userDetail.Viplevel,
            nickname: this.props.userDetail.Nickname,
            uid: this.props.userDetail.Id,
            vip: this.props.userDetail.Vip,
        }

        // const data = JSON.stringify(m)
        const propid = 0
        const to = this.matchId
        const propnum = 0
        const game = this.props.currentGame.matchevent.name_zh
        const usepacket = 0
        sendChatMsgReq({
            uid: this.uid,
            to,
            propid,
            propnum,
            game,
            usepacket,
            data: JSON.stringify(m),
            Flag: this.props.chatFlag,
        })

    }
    // 确认发送礼物
    sendGift = (gift) => {

        gift.c = 2
        // gift.uid = this.state.uid
        // gift.giver = this.props.userDetail.Nickname
        const game = this.props.currentGame.matchevent.name_zh
        gift.viplevel = this.props.userDetail.Viplevel
        gift.nickname = this.props.userDetail.Nickname
        gift.uid = this.props.userDetail.Id
        gift.vip = this.props.userDetail.Vip
        gift.game = game
        gift.anchorName = '平台'
        gift.giftId = gift.Id
        gift.name = gift.Name


        // const data = JSON.stringify(m)

        // UsePack: false
        // anchorName: "平台"
        // c: 2
        // game: "哥斯达黎加甲组联赛"

        // giftId: 8
        // giftnum: 1
        // name: "赞"
        // nickname: "Allen"
        // price: 1
        // selected: false
        // uid: "3b9ebae0-9049-4e65-959f-afb59f1a1ec4"
        // vip: 11
        // viplevel: 5
        const propid = gift.Id
        const to = this.matchId
        const propnum = gift.giftnum
        const usepacket = gift.UsePack ? 1 : 0

        return sendChatMsgReq({
            uid: this.uid,
            to,
            propid,
            propnum,
            game,
            usepacket,
            data: JSON.stringify(gift),
            nosave: 1,
        }).then((data) => {

            if (data.data.err) {
                Toast.info(constants.ErrorCode[data.data.err])
            }
        })

        // const d = JSON.stringify(gift)
        // this.props.chatWs.send(d)



    }

    checkWsErr = () => {
        const e = this.props.chat.err
        if (e > 0) {
            Toast.info(constants.WsErrorCode[e])
        }
        this.props.doEmptyWsErr()
    }

    render() {

        const {
            giftNotice,
            // goalNotice,
            userDetail,} = this.props
        // console.log(this.props)

        const giftNoticesTemplate = this.props.gifts.map((gift, index) => {
            if (gift.showed) {
                return false
            } else {
                log('gift')
                return <GiftNotice
                    gift={gift}
                    key={index}
                    // iconIndex={index}
                    onAnimationEnd={(e) => this.onAnimationEnd(index, e)}
                />
            }
        })

        return (
            <>
                <div
                    style={{height: '100%',}}
                    ref={el => this.ctnContent = el}
                >
                    <DialogueContainer
                        dialogues={this.props.dialogues}
                        inputTouched={this.state.inputTouched}
                    />

                    {/*{goalNotice ? <GoalSpeaker /> : null}*/}
                    {giftNotice ? giftNoticesTemplate : null}
                    <GiftPopup
                        visible={this.state.popUp.gift}
                        // visible={true}
                        userDetail={userDetail}
                        onClose={this.onClose}
                        onSendGift={this.sendGift}
                        afterClose={() => this.checkWsErr()}
                    />
                    <ConsumePopup
                        userDetail={userDetail}
                        visible={this.state.popUp.consume}
                        onClose={this.onClose}
                    />
                    <ChatRoomFooter
                        onPopUp={this.onPopUp}
                        onInputFocus={this.onInputFocus}
                        onInputBlur={this.onInputBlur}
                        onChatInputChange={this.onChatInputChange}
                        onChatInputSubmit={this.onChatInputSubmit}
                        inputValue={this.state.msg}
                        inputDisabled={!(LocalStorageService.get('isLogin') === true)}
                        basketball
                    />
                    {giftNotice ? giftNoticesTemplate : null}
                </div>
            </>

        )
    }

}
// const mapStatesToProps = ({global: {isLogin,}, user:{userdetail,},}) => ({
//     isLogin,
//     userdetail,
// })

const mapStatesToProps = (state) => ({
    isLogin: state.global.isLogin,
    userDetail: state.user.userdetail,
    chat: state.chat,
    chatWs: state.chat.chatWs,
    users: state.chat.users,
    dialogues: state.chat.dialogues,
    gifts: state.chat.gifts,
    liveDetail: state.live.liveDetail,
    currentGame: state.game.currentGame,
    chatRoomToken: state.game.chatRoomToken,
})

const mapDispatchToProps = (dispatch) => ({
    fetchUserDetail: (id) => dispatch.user.fetchUserDetail(id),
    doGetGameRoomChatToken: (payload) => dispatch.game.doGetGameRoomChatToken(payload),
    onConnectWs: (payload) => dispatch.chat.onConnectWs(payload),
    onChatWsClose: (payload) => dispatch.chat.onChatWsClose(payload),
    doEmptyWsErr: () => dispatch.chat.doEmptyWsErr(),
    doGetChatExp: () => dispatch.exp.doGetChatExp(),
    doGetChatToken: (payload) => dispatch.chat.doGetChatToken(payload),
})

export default connect(
    mapStatesToProps,
    mapDispatchToProps,
)(withRouter(ChatRoom))


